using Infrastructure;
using Infrastructure.Attribute;
using System.Text.Json;
using ZR.Model.System.Dto;
using ZR.ServiceCore.Services.IService;

namespace ZR.ServiceCore.Services
{
    /// <summary>
    /// 雷达初始化服务实现
    /// </summary>
    [AppService(ServiceType = typeof(IWindLidarInitService), ServiceLifetime = LifeTime.Transient)]
    public class WindLidarInitService : IWindLidarInitService
    {
        private readonly HttpClient _httpClient;
        private const string API_URL = "http://leida.vip.cpolar.cn/api/windlidar/init";
        private const string STOP_API_URL = "http://leida.vip.cpolar.cn/api/windlidar/stop";
        private const string START_API_URL = "http://leida.vip.cpolar.cn/api/windlidar/start";

        public WindLidarInitService(HttpClient httpClient)
        {
            _httpClient = httpClient;
        }

        /// <summary>
        /// 执行雷达初始化（异步方法）
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        public async Task<WindLidarInitResultDto> InitWindLidarAsync(WindLidarInitRequestDto request = null)
        {
            try
            {
                // 设置默认参数
                if (request == null)
                {
                    request = new WindLidarInitRequestDto
                    {
                        CommandType = "init",
                        CommandData = null
                    };
                }

                // 构建请求内容
                var requestContent = new
                {
                    commandtype = request.CommandType,
                    commanddata = request.CommandData
                };

                var jsonContent = System.Text.Json.JsonSerializer.Serialize(requestContent);
                var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");

                Console.WriteLine($"雷达初始化 - 发送请求到: {API_URL}");
                Console.WriteLine($"雷达初始化 - 请求内容: {jsonContent}");

                // 发送POST请求
                var response = await _httpClient.PostAsync(API_URL, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"雷达初始化 - 响应状态码: {response.StatusCode}");
                Console.WriteLine($"雷达初始化 - 响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应
                    var initResponse = System.Text.Json.JsonSerializer.Deserialize<WindLidarInitResponseDto>(responseContent, new System.Text.Json.JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    var dataValue = initResponse?.GetData() ?? false;
                    var messageValue = initResponse?.GetMessage() ?? "无消息";
                    var detailValue = initResponse?.GetDetail() ?? "无详细信息";
                    Console.WriteLine($"雷达初始化 - JSON解析完成，Success: {initResponse?.Success}, Data: {dataValue}, Message: {messageValue}, Detail: {detailValue}");
                    
                    if (initResponse != null)
                    {
                        return ConvertToResultDto(initResponse);
                    }
                    else
                    {
                        return new WindLidarInitResultDto
                        {
                            IsSuccess = false,
                            Message = "响应解析失败",
                            Detail = "无法解析第三方接口响应",
                            QueryTime = DateTime.Now,
                            StatusDescription = "解析失败"
                        };
                    }
                }
                else
                {
                    return new WindLidarInitResultDto
                    {
                        IsSuccess = false,
                        Message = $"HTTP请求失败: {response.StatusCode}",
                        Detail = responseContent,
                        QueryTime = DateTime.Now,
                        StatusDescription = "请求失败"
                    };
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"雷达初始化 - HTTP请求异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "网络请求失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "网络异常"
                };
            }
            catch (System.Text.Json.JsonException ex)
            {
                Console.WriteLine($"雷达初始化 - JSON解析异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "响应解析失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "解析异常"
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"雷达初始化 - 未知异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "系统异常",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "系统异常"
                };
            }
        }

        /// <summary>
        /// 转换为结果DTO
        /// </summary>
        /// <param name="response">原始响应数据</param>
        /// <returns></returns>
        private WindLidarInitResultDto ConvertToResultDto(WindLidarInitResponseDto response)
        {
            return new WindLidarInitResultDto
            {
                IsSuccess = response.Success,
                Message = response.GetMessage() ?? "无消息",
                Detail = response.GetDetail() ?? "无详细信息",
                QueryTime = DateTime.Now,
                StatusDescription = GetInitStatusDescription(response.Success)
            };
        }

        /// <summary>
        /// 停止采集（异步方法）
        /// </summary>
        /// <returns></returns>
        public async Task<WindLidarInitResultDto> StopWindLidarAsync()
        {
            try
            {
                // 构建请求内容（参数写死）
                var requestContent = new
                {
                    commandtype = "stop",
                    commanddata = (object)null
                };

                var jsonContent = System.Text.Json.JsonSerializer.Serialize(requestContent);
                var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");

                Console.WriteLine($"停止采集 - 发送请求到: {STOP_API_URL}");
                Console.WriteLine($"停止采集 - 请求内容: {jsonContent}");

                // 发送POST请求
                var response = await _httpClient.PostAsync(STOP_API_URL, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"停止采集 - 响应状态码: {response.StatusCode}");
                Console.WriteLine($"停止采集 - 响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应
                    var stopResponse = System.Text.Json.JsonSerializer.Deserialize<WindLidarInitResponseDto>(responseContent, new System.Text.Json.JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    var stopDataValue = stopResponse?.GetData() ?? false;
                    var stopMessageValue = stopResponse?.GetMessage() ?? "无消息";
                    var stopDetailValue = stopResponse?.GetDetail() ?? "无详细信息";
                    Console.WriteLine($"停止采集 - JSON解析完成，Success: {stopResponse?.Success}, Data: {stopDataValue}, Message: {stopMessageValue}, Detail: {stopDetailValue}");
                    
                    if (stopResponse != null)
                    {
                        return ConvertToStopResultDto(stopResponse);
                    }
                    else
                    {
                        return new WindLidarInitResultDto
                        {
                            IsSuccess = false,
                            Message = "响应解析失败",
                            Detail = "无法解析第三方接口响应",
                            QueryTime = DateTime.Now,
                            StatusDescription = "解析失败"
                        };
                    }
                }
                else
                {
                    return new WindLidarInitResultDto
                    {
                        IsSuccess = false,
                        Message = $"HTTP请求失败: {response.StatusCode}",
                        Detail = responseContent,
                        QueryTime = DateTime.Now,
                        StatusDescription = "请求失败"
                    };
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"停止采集 - HTTP请求异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "网络请求失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "网络异常"
                };
            }
            catch (System.Text.Json.JsonException ex)
            {
                Console.WriteLine($"停止采集 - JSON解析异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "响应解析失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "解析异常"
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"停止采集 - 未知异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "系统异常",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "系统异常"
                };
            }
        }

        /// <summary>
        /// 转换为停止采集结果DTO
        /// </summary>
        /// <param name="response">原始响应数据</param>
        /// <returns></returns>
        private WindLidarInitResultDto ConvertToStopResultDto(WindLidarInitResponseDto response)
        {
            return new WindLidarInitResultDto
            {
                IsSuccess = response.Success,
                Message = response.GetMessage() ?? "无消息",
                Detail = response.GetDetail() ?? "无详细信息",
                QueryTime = DateTime.Now,
                StatusDescription = GetStopStatusDescription(response.Success)
            };
        }

        /// <summary>
        /// 获取初始化状态描述
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <returns></returns>
        private string GetInitStatusDescription(bool success)
        {
            return success ? "初始化成功" : "初始化失败";
        }

        /// <summary>
        /// 获取停止采集状态描述
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <returns></returns>
        private string GetStopStatusDescription(bool success)
        {
            return success ? "停止采集成功" : "停止采集失败";
        }

        /// <summary>
        /// 开始采集（异步方法）
        /// </summary>
        /// <param name="request">请求参数</param>
        /// <returns></returns>
        public async Task<WindLidarInitResultDto> StartWindLidarAsync(WindLidarStartRequestDto request)
        {
            try
            {
                if (request == null || string.IsNullOrEmpty(request.Type))
                {
                    return new WindLidarInitResultDto
                    {
                        IsSuccess = false,
                        Message = "参数错误",
                        Detail = "类型参数不能为空",
                        QueryTime = DateTime.Now,
                        StatusDescription = "参数错误"
                    };
                }

                object requestContent;
                var type = request.Type.ToUpper();

                if (type == "DBS")
                {
                    // DBS 模式
                    if (!request.MaxRange.HasValue || !request.RangeResolution.HasValue)
                    {
                        return new WindLidarInitResultDto
                        {
                            IsSuccess = false,
                            Message = "参数错误",
                            Detail = "DBS模式需要提供maxrange和rangeresolution参数",
                            QueryTime = DateTime.Now,
                            StatusDescription = "参数错误"
                        };
                    }

                    requestContent = new
                    {
                        commandtype = "start",
                        type = "DBS",
                        commanddata = new
                        {
                            name = "DBS_Task",
                            cycles = 1,
                            interval = 60,
                            maxrange = request.MaxRange.Value,
                            pulsewidth = 200,
                            CNRthreshold = 10,
                            scantype = 7,
                            cutnumber = 1,
                            elevationstart = 0,
                            elevationend = 60,
                            elevationstep = 30,
                            sample = 128,
                            tasks = new[]
                            {
                                new
                                {
                                    scaninstance = "DBS",
                                    beamnumber = 6,
                                    shots = 10000,
                                    rangeresolution = request.RangeResolution.Value,
                                    scanspeed = 90,
                                    cycles = 1,
                                    interval = 60
                                }
                            }
                        }
                    };
                }
                else if (type == "PPI")
                {
                    // PPI 模式
                    if (!request.MaxRange.HasValue || !request.RangeResolution.HasValue ||
                        !request.AzimuthStart.HasValue || !request.AzimuthEnd.HasValue ||
                        !request.Elevation.HasValue || !request.AngleResolution.HasValue)
                    {
                        return new WindLidarInitResultDto
                        {
                            IsSuccess = false,
                            Message = "参数错误",
                            Detail = "PPI模式需要提供maxrange、rangeresolution、azimuthstart、azimuthend、elevation和angleresolution参数",
                            QueryTime = DateTime.Now,
                            StatusDescription = "参数错误"
                        };
                    }

                    requestContent = new
                    {
                        commandtype = "start",
                        type = "PPI",
                        commanddata = new
                        {
                            name = "PPI_Task",
                            cycles = 0,
                            interval = 0,
                            maxrange = request.MaxRange.Value,
                            pulsewidth = 200,
                            CNRthreshold = 10,
                            scantype = 2,
                            cutnumber = 1,
                            elevationstart = 0,
                            elevationend = 0,
                            elevationstep = 0,
                            sample = 2000,
                            tasks = new[]
                            {
                                new
                                {
                                    azimuthstart = request.AzimuthStart.Value,
                                    azimuthend = request.AzimuthEnd.Value,
                                    elevation = request.Elevation.Value,
                                    direction = 0,
                                    angleresolution = request.AngleResolution.Value,
                                    scaninstance = "PPI",
                                    beamnumber = 0,
                                    shots = 1500,
                                    scanspeed = 30,
                                    cycles = 0,
                                    rangeresolution = request.RangeResolution.Value,
                                    interval = 60
                                }
                            }
                        }
                    };
                }
                else
                {
                    return new WindLidarInitResultDto
                    {
                        IsSuccess = false,
                        Message = "参数错误",
                        Detail = $"不支持的类型: {request.Type}，只支持DBS或PPI",
                        QueryTime = DateTime.Now,
                        StatusDescription = "参数错误"
                    };
                }

                var jsonContent = System.Text.Json.JsonSerializer.Serialize(requestContent);
                var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");

                Console.WriteLine($"开始采集 - 发送请求到: {START_API_URL}");
                Console.WriteLine($"开始采集 - 请求内容: {jsonContent}");

                // 发送POST请求
                var response = await _httpClient.PostAsync(START_API_URL, content);
                var responseContent = await response.Content.ReadAsStringAsync();

                Console.WriteLine($"开始采集 - 响应状态码: {response.StatusCode}");
                Console.WriteLine($"开始采集 - 响应内容: {responseContent}");

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应
                    var startResponse = System.Text.Json.JsonSerializer.Deserialize<WindLidarInitResponseDto>(responseContent, new System.Text.Json.JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    });
                    
                    var startDataValue = startResponse?.GetData() ?? false;
                    var startMessageValue = startResponse?.GetMessage() ?? "无消息";
                    var startDetailValue = startResponse?.GetDetail() ?? "无详细信息";
                    Console.WriteLine($"开始采集 - JSON解析完成，Success: {startResponse?.Success}, Data: {startDataValue}, Message: {startMessageValue}, Detail: {startDetailValue}");
                    
                    if (startResponse != null)
                    {
                        return ConvertToStartResultDto(startResponse);
                    }
                    else
                    {
                        return new WindLidarInitResultDto
                        {
                            IsSuccess = false,
                            Message = "响应解析失败",
                            Detail = "无法解析第三方接口响应",
                            QueryTime = DateTime.Now,
                            StatusDescription = "解析失败"
                        };
                    }
                }
                else
                {
                    return new WindLidarInitResultDto
                    {
                        IsSuccess = false,
                        Message = $"HTTP请求失败: {response.StatusCode}",
                        Detail = responseContent,
                        QueryTime = DateTime.Now,
                        StatusDescription = "请求失败"
                    };
                }
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"开始采集 - HTTP请求异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "网络请求失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "网络异常"
                };
            }
            catch (System.Text.Json.JsonException ex)
            {
                Console.WriteLine($"开始采集 - JSON解析异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "响应解析失败",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "解析异常"
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine($"开始采集 - 未知异常: {ex.Message}");
                return new WindLidarInitResultDto
                {
                    IsSuccess = false,
                    Message = "系统异常",
                    Detail = ex.Message,
                    QueryTime = DateTime.Now,
                    StatusDescription = "系统异常"
                };
            }
        }

        /// <summary>
        /// 转换为开始采集结果DTO
        /// </summary>
        /// <param name="response">原始响应数据</param>
        /// <returns></returns>
        private WindLidarInitResultDto ConvertToStartResultDto(WindLidarInitResponseDto response)
        {
            return new WindLidarInitResultDto
            {
                IsSuccess = response.Success,
                Message = response.GetMessage() ?? "无消息",
                Detail = response.GetDetail() ?? "无详细信息",
                QueryTime = DateTime.Now,
                StatusDescription = GetStartStatusDescription(response.Success)
            };
        }

        /// <summary>
        /// 获取开始采集状态描述
        /// </summary>
        /// <param name="success">请求是否成功</param>
        /// <returns></returns>
        private string GetStartStatusDescription(bool success)
        {
            return success ? "开始采集成功" : "开始采集失败";
        }
    }
}
